
在Java中捕捉Exceptions,可以用try/catch來完成。格式如下:
try
{
   //Code
}catch(ExceptionName e1)
{
   //Catch block
}
"Code"的部分是你想要監視的程式,一旦出現"ExceptionName"所指定的Exception,就會執行"Catch block"的程式。以下是例子:
import java.io.*;
public class ExcepTest{
   public static void main(String args[]){
      try{
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}
結果顯示如下:
Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
[image credit: PAULA BOROWSKA]